<template>
  <div class="user-container">
    <div class="user-header">
      <!-- 搜索表单 -->
      <div class="search-wrapper">
        <el-form :inline="true" :model="queryParams" class="search-form">
          <el-form-item label="用户名">
            <el-input 
              v-model="queryParams.username" 
              placeholder="请输入用户名" 
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input 
              v-model="queryParams.phone" 
              placeholder="请输入手机号" 
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="queryParams.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="启用" value="enabled">
                <el-icon color="#67C23A"><CircleCheck /></el-icon>
                <span style="margin-left: 8px">启用</span>
              </el-option>
              <el-option label="禁用" value="disabled">
                <el-icon color="#909399"><CircleClose /></el-icon>
                <span style="margin-left: 8px">禁用</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>搜索
              </el-button>
              <el-button @click="resetQuery">
                <el-icon><Refresh /></el-icon>重置
              </el-button>
            </el-button-group>
          </el-form-item>
        </el-form>

        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增用户
        </el-button>
      </div>

      <!-- 数据统计卡片 -->
      <div class="stat-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="card-header">
                  <span>总用户数</span>
                  <el-tag type="info" effect="plain">全部</el-tag>
                </div>
              </template>
              <div class="card-body">
                <span class="number">{{ stats.total }}</span>
                <span class="label">个</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="card-header">
                  <span>启用用户</span>
                  <el-tag type="success" effect="plain">正常</el-tag>
                </div>
              </template>
              <div class="card-body">
                <span class="number">{{ stats.enabled }}</span>
                <span class="label">个</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="card-header">
                  <span>禁用用户</span>
                  <el-tag type="info" effect="plain">已禁用</el-tag>
                </div>
              </template>
              <div class="card-body">
                <span class="number">{{ stats.disabled }}</span>
                <span class="label">个</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="card-header">
                  <span>今日新增</span>
                  <el-tag type="warning" effect="plain">新增</el-tag>
                </div>
              </template>
              <div class="card-body">
                <span class="number">{{ stats.today }}</span>
                <span class="label">个</span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="user-content">
      <el-table :data="userList" style="width: 100%">
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="roles" label="角色" min-width="120">
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role" size="small" style="margin-right: 4px">
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="'enabled'"
              :inactive-value="'disabled'"
              @change="handleStatusChange(row)"
              :disabled="row.username === 'admin'"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="primary" link @click="handleResetPwd(row)">
              重置密码
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              :disabled="row.username === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formType === 'add' ? '新增用户' : '编辑用户'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="formData.username" 
            placeholder="请输入用户名"
            :disabled="formType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="���机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="formData.roles"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="formType === 'add'">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="formType === 'add'">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请确认密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="formData.status"
            active-value="enabled"
            inactive-value="disabled"
            :disabled="formData.username === 'admin'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPwdVisible"
      title="重置密码"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="resetPwdForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPwdForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPwdVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPwdSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { 
  Plus, 
  Search, 
  Refresh,
  User,
  Phone,
  CircleCheck,
  CircleClose
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 查询参数
const queryParams = ref({
  username: '',
  phone: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

// 统计数据
const stats = ref({
  total: 125,
  enabled: 108,
  disabled: 17,
  today: 5
})

// 用户列表数据
const userList = ref([
  {
    id: 1,
    username: 'admin',
    nickname: '超级管理员',
    phone: '13800138000',
    email: 'admin@example.com',
    roles: ['超级管理员'],
    createTime: '2024-01-01 00:00:00',
    status: 'enabled'
  },
  {
    id: 2,
    username: 'test',
    nickname: '测试用户',
    phone: '13800138001',
    email: 'test@example.com',
    roles: ['普通用户'],
    createTime: '2024-01-01 00:00:00',
    status: 'enabled'
  }
])

// 角色选项
const roleOptions = [
  { label: '超级管理员', value: '超级管理员' },
  { label: '普通用户', value: '普通用户' }
]

// 表单相关
const dialogVisible = ref(false)
const formType = ref('add')
const formRef = ref(null)
const formData = ref({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  roles: [],
  password: '',
  confirmPassword: '',
  status: 'enabled'
})

// 表单校验规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '用户名只能包含字母、数字和下划线，且必须以字母开头', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 重置密码相关
const resetPwdVisible = ref(false)
const resetPwdFormRef = ref(null)
const resetPwdForm = ref({
  userId: null,
  password: '',
  confirmPassword: ''
})

// 重置密码校验规则
const resetPwdRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPwdForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 搜索
const handleSearch = () => {
  queryParams.value.pageNum = 1
  // TODO: 调用搜索接口
  ElMessage.success('搜索成功')
  console.log('搜索参数:', queryParams.value)
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    username: '',
    phone: '',
    status: '',
    pageNum: 1,
    pageSize: 10
  }
  handleSearch()
  ElMessage.success('重置成功')
}

// 新增用户
const handleAdd = () => {
  formType.value = 'add'
  formData.value = {
    username: '',
    nickname: '',
    phone: '',
    email: '',
    roles: [],
    password: '',
    confirmPassword: '',
    status: 'enabled'
  }
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  formType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('超级管理员不能删除')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 调用删除接口
    ElMessage.success('删除成功')
  })
}

// 状态变更
const handleStatusChange = (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('超级管理员状态不能修改')
    row.status = 'enabled'
    return
  }
  // TODO: 调用状态修改接口
  ElMessage.success('状态修改成功')
}

// 重置密码
const handleResetPwd = (row) => {
  resetPwdForm.value = {
    userId: row.id,
    password: '',
    confirmPassword: ''
  }
  resetPwdVisible.value = true
}

// 提交重置密码
const handleResetPwdSubmit = () => {
  resetPwdFormRef.value?.validate((valid) => {
    if (valid) {
      // TODO: 调用重置密码接口
      ElMessage.success('密码重置成功')
      resetPwdVisible.value = false
    }
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      // TODO: 调用保存接口
      ElMessage.success(formType.value === 'add' ? '新增成功' : '修改成功')
      dialogVisible.value = false
    }
  })
}

// 分页相关
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  handleSearch()
}
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.user-header {
  margin-bottom: 20px;
}

.search-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.search-form {
  flex: 1;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset !important;
}

:deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset !important;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body {
  text-align: center;
  padding: 10px 0;
}

.number {
  font-size: 28px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-right: 4px;
}

.label {
  font-size: 14px;
  color: #909399;
}

:deep(.el-card__header) {
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-tag) {
  border-radius: 12px;
}

.user-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 暗黑模式适配 */
:deep(html.dark) .search-wrapper,
:deep(html.dark) .user-content {
  background: var(--el-bg-color);
  box-shadow: none;
}

:deep(html.dark) .el-input__wrapper,
:deep(html.dark) .el-select .el-input__wrapper {
  box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
}

:deep(html.dark) .el-input__wrapper:hover,
:deep(html.dark) .el-select .el-input__wrapper:hover {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset !important;
}
</style> 